define(function (require) {
    require('common/fileuploader');
    require('validate');
    require('layer_ui');

    var Base = require('group/common/main');
    var utils = require('common/utils/home');
    var waterfall = require('common/waterfall');
    var Mask = require('common/mask');
    var mask = new Mask();
    var ItemCommentTpl = require('text!./templates/item_comment.html');

    return Base.extend({
        initialize: function (params) {
            var _this = this;
            Base.prototype.initialize.apply(this, [params]);
            if (_this['page_' + _global.a]) {
                _this['page_' + _global.a]();
            }
        },
        submit_reload: function (url) {
            var _this = this;
            _this.$('form').validate({
                submitHandler: function (form) {
                    var params = _this.$('form').serializeJson();
                    utils.ajaxPost(params, function (resp) {
                        mask.success(resp.msg, function () {
                            if (url) {
                                window.location.href = url;
                            }
                            else {
                                window.location.reload();
                            }

                        });
                    });
                }
            });
        },
        page_feedback: function () {
            var _this = this;
            _this.bind_submit('谢谢反馈');
        },
        page_edit_password: function () {
            var _this = this;
            _this.bind_submit();
        },
        page_profile: function () {
            var _this = this;
            _this.initUpload({
                queueSizeLimit: 1,
                removeCompleted: true,
                onUpload: function () {
                    _this.$('.uploadifive-queue').show();
                },
                _onUploadComplete: function (file, data) {
                    _this.$('.uploadifive-queue').hide();
                    _this.$('.upload_avatar .avatar').attr('src', data.data.fullPath);
                    _this.$('#J_img_hidden').val(data.data.savePath);
                }
            });
            _this.submit_reload();
        },
        page_add_address: function () {
            var _this = this;
            utils.cate_select();

            _this.validate({
                fn: function (params) {
                    if (_.empty($('input[name="province"]').val()) || _.empty($('input[name="city"]').val())) {
                        return layer.msg('省市县都必须选择!');
                    }
                    utils.ajaxPost(_.extend({a: 'ajax_save_address'}, params), function (resp) {
                        mask.success(resp.msg, function () {
                            if (resp.url) {
                                _this.refresh_address_id(resp.url, resp.address_id);
                            }
                            else {
                                window.location.href = _.U({a: 'address'});
                            }
                        });
                    });
                }
            });

            utils.loadAddress();
        },
        page_edit_address: function () {
            this.page_add_address();
        },
        page_address: function () {
            var _this = this;
            _this.$('.J_del').click(function () {
                var id = $(this).parents('.J_item').data('id');
                layer.confirm('确定要删除吗?', function () {
                    utils.ajaxPost({a: 'delete_address', id: id}, function () {
                        window.location.reload();
                    });
                });
            });
            _this.$('.J_set_default').click(function () {
                var $this = $(this);
                var id = $this.parents('.J_item').data('id');
                utils.ajaxPost({a: 'address_set_default', id: id}, function () {
                    mask.success('设置成功');
                    _this.$('.J_set_default').prop('checked', false);
                    $this.prop('checked', true);
                });
            });
            _this.$('.J_select').click(function (e) {
                var $item = $(this).parents('.J_item');
                var ret_url = $item.data('ret_url').trim();
                if (_.empty(ret_url)) {
                    return;
                }
                _this.refresh_address_id(ret_url, $item.data('id'));
            });
        },
        refresh_address_id: function (ret_url, address_id) {
            var res = _.parse_url(_.base64_decode(ret_url));
            var url = res.scheme + '://' + res.host + res.path;
            var url_query = _.parse_query(_.base64_decode(ret_url));

            url_query.address_id = address_id;
            window.location.href = url + '?' + _.http_build_query(url_query);
        },
        page_favs: function () {
            var _this = this;
            _this.waterfall();
            new Swiper('.item-rec', {
                slidesPerView: 3.4
            });
        },
        page_order: function () {
            var _this = this;

            function bind_confirm_receive() {
                _this.bind_order_refund();
                _this.$('.J_confirm_receive').unbind('click').click(function () {
                    var $this = $(this);
                    layer.confirm('确认要收货吗?', function () {
                        utils.ajaxPost({a: 'order_confirm_receive', id: $this.data('id')}, function () {
                            window.location.reload();
                        });
                    });
                });
            }

            _this.waterfall({
                fn: function () {
                    bind_confirm_receive();
                }
            });
            bind_confirm_receive();
            _this.$('.J_member_contact').click(function () {
                var $this = $(this);
                layer.open({
                    type: 2,
                    title: '商家客服',
                    shadeClose: true,
                    shade: 0.8,
                    area: ['100%', '100%'],
                    content: _.U({m: 'member', a: 'contact', mid: $this.data('mid'), iframe: '1'})
                });
            });
        },
        bind_order_refund: function () {
            var _this = this;
            _this.$('.J_refund_order').unbind('click').on('click', function () {
                var $this = $(this);
                var order_id = $this.data('id');
                utils.ajaxGet({a: 'ajax_refund_order', id: order_id, act: 'tip'}, function (resp) {
                    layer.confirm(resp.data.tip, {title: '退款信息'}, function () {
                        utils.ajaxPost({a: 'ajax_refund_order', id: $this.data('id')}, function (resp) {
                            layer.closeAll();
                            mask.success(resp.data.tip, function () {
                                window.location.reload();
                            });
                        });
                    });
                }, function (resp) {
                    mask.error(resp.msg, function () {
                        if (resp.data.url) {
                            window.location.href = resp.data.url;
                        }
                    });
                });
            });
            $('.J_express_info').unbind('click').on('click', function () {
                $.ajax({
                    url: _.U({a: 'express'}),
                    type: 'POST',
                    data: {id: $(this).attr('data-id')},
                    dataType: 'HTML',
                    success: function (result) {
                        layer.confirm(result, function () {

                        });
                        $('.layui-layer-btn0').hide();
                        $('.layui-layer-title').text('物流详情');
                    }
                });
            });
            $('.J_take_delivery').unbind('click').click(function () {
                //合并订单
                var $this = $(this);
                var id = $this.data('id');
                $.ajax({
                    url:_.U({m: 'user',a: 'sum_order'}),
                    type:'GET',
                    data:{ id: id},
                    dataType:'JSON',
                    success:function(resp){
                        if(resp.status == 1){
                            layer.confirm('一共有'+resp.num+'个相同的商品'+',合并提货？',{
                                btn: ['合并','取消'] //按钮
                            },function () {//合并
                                var $this = $(this);

                                layer.confirm('运费6元，是否合并', {
                                    btn: ['确定','取消'] //按钮
                                }, function(){
                                    //layer.msg('的确很重要', {icon: 1});
                                    var $this = $(this);
                                  //  alert(id);
                                    $.ajax({
                                        url:_.U({m: 'user',a: 'do_sum'}),
                                        type:'GET',
                                        data:{ id: id},
                                        dataType:'JSON',
                                        success:function(ress){
                                            var $this = $(this);
                                           // alert(id);
                                            if(ress.do_sum_o == 2){
                                               // window.location.href = _.U({m: 'user',a: 'order_address',id:id});
                                                layer.msg('合并成功', {icon: 1});
                                                utils.ajaxPost({a: 'order_take_delivery', id: id}, function (res) {
                                                    // if(res.error == 2){
                                                    //     layer.confirm('余额不足,请充值!', {
                                                    //             title: '提示',
                                                    //             btn: ['去充值','关闭'] //按钮
                                                    //         },
                                                    //         function(){
                                                    //             window.location.href = _.U({
                                                    //                 m: 'user',
                                                    //                 a: 'recharge',
                                                    //             });
                                                    //         }, function(){
                                                    //             layer.close();
                                                    //         });
                                                    //     return;
                                                   // }else{
                                                        window.location.href = _.U({m: 'user',a: 'order_address',id:id});
                                                 //   }
                                                });
                                            }
                                        }
                                    });
                                }, function(){
                                    layer.msg('已取消', {icon: 1});
                                });

                            },function () {//取消
                                // layer.confirm('直接提货', function () {
                                layer.confirm('需要支付运费'+_global.express+'元，是否直接提货?', function () {
                                    utils.ajaxPost({a: 'order_take_delivery', id: id}, function (res) {
                                        if(res.error == 2){
                                            layer.confirm('余额不足,请充值!', {
                                                    title: '提示',
                                                    btn: ['去充值','关闭'] //按钮
                                                },
                                                function(){
                                                    window.location.href = _.U({
                                                        m: 'user',
                                                        a: 'recharge',
                                                    });
                                                }, function(){
                                                    layer.close();
                                                });
                                            return;
                                        }else{
                                            window.location.href = _.U({m: 'user',a: 'order_address',id:id});
                                        }
                                    });
                                });
                            });
                        }else{
                            //没有相同的商品
                            layer.confirm('需要支付运费'+_global.express+'元，是否提货?', function () {
                                utils.ajaxPost({a: 'order_take_delivery', id: id}, function (res) {
                                    if(res.error == 2){
                                        layer.confirm('余额不足,请充值!', {
                                                title: '提示',
                                                btn: ['去充值','关闭'] //按钮
                                            },
                                            function(){
                                                window.location.href = _.U({
                                                    m: 'user',
                                                    a: 'recharge',
                                                });
                                            }, function(){
                                                layer.close();
                                            });
                                        return;
                                    }else{
                                        window.location.href = _.U({m: 'user',a: 'order_address',id:id});
                                    }
                                });
                            });
                        }
                    }
                });

            });
        },
        //****************************************************************************

//         $('.J_take_order').unbind('click').click(function () {
//         var $this = $(this);
//         layer.confirm('需要支付运费'+_global.express+'元，是否提货?', function () {
//             utils.ajaxPost({a: 'order_take_delivery', id: $this.data('id')}, function (res) {
//                 if(res.error == 2){
//                     layer.confirm('余额不足,请充值!', {
//                             title: '提示',
//                             btn: ['去充值','关闭'] //按钮
//                         },
//                         function(){
//                             window.location.href = _.U({
//                                 m: 'user',
//                                 a: 'recharge',
//                             });
//                         }, function(){
//                             layer.close();
//                         });
//                     return;
//                 }else{
//                     window.location.href = _.U({m: 'user',a: 'order_address',id:$this.data('id')});
//                 }
//             });
//         });
//     });
// },
        //****************************************************************************

        page_order_info: function () {
            var _this = this;
            _this.$('#J_confirm_receive').click(function () {
                var $this = $(this);
                layer.confirm('确认要收货吗?', function () {
                    utils.ajaxPost({a: 'order_confirm_receive', id: $this.data('id')}, function () {
                        window.location.reload();
                    });
                });
            });
            _this.bind_order_refund();
        },
        page_order_comment: function () {
            var _this = this;
            _this.initUpload({queueSizeLimit: 9});
            _this.$('form').validate({
                submitHandler: function (form) {
                    var params = _this.$('form').serializeJson();
                    utils.ajaxPost(params, function (resp) {
                        mask.success(resp.data, function () {
                            history.back();
                        });
                    });
                }
            });
        },
        page_comment_list: function () {
            var _this = this;
            var comment_waterfall = new waterfall({
                container: '#J_waterfall_comment',
                loading_bar: '#J_wall_loading_comment',
                spage: 1,
                auto_load: false,
                ajax_url: _.U({act: 'ajax_fetch'}),
                content_html: function (resp) {
                    return _this.render(ItemCommentTpl, resp.data);
                }
            });
            comment_waterfall.start({
                spage: 1
            });
            _this.$('#J_item_comment_title a').click(function () {
                $(this).addClass('ac').siblings().removeClass('ac');
            });
            _this.$('#J_item_comment_all').click(function () {
                comment_waterfall.start({
                    spage: 1,
                    ajax_params: {type: 'all'}
                });
            });
            _this.$('#J_item_comment_img').click(function () {
                comment_waterfall.start({
                    spage: 1,
                    ajax_params: {type: 'img'}
                });
            });
        },
        page_score_list: function () {
            var _this = this;
            var score_waterfall = new waterfall({
                spage: 1,
                auto_load: false,
                ajax_url: _.U({}),
                content_html: function (resp) {
                    return _this.render(require('text!./templates/score_list.html'), resp.data);
                }
            });

            var index = 0;
            if (window.location.hash == '#score_logs_type_10') {
                index = 1;
            }
            _this.$('.nav .item').eq(index).addClass('choise');
            score_waterfall.start({
                spage: 1,
                ajax_params: {
                    type: _this.$('.nav .item').eq(index).data('type')
                }
            });
            _this.$('.nav .item').click(function () {
                var $this = $(this);
                _this.$('.nav .item').removeClass('choise');
                $this.addClass('choise');

                score_waterfall.start({
                    spage: 1,
                    ajax_params: {
                        type: $this.data('type')
                    }
                });
            });
        },
        page_score_apply: function () {
            var _this = this;
            _this.$('form').validate({
                submitHandler: function (form) {
                    var params = _this.$('form').serializeJson();
                    utils.ajaxPost(_.extend({act: 'validate'}, params), function (resp) {
                        layer.confirm('兑换数量：' + resp.data.score_apply + ', 其中服务费用：' + resp.data.fee, function () {
                            utils.ajaxPost(params, function (resp) {
                                layer.closeAll();
                                mask.success(resp.msg, function () {
                                    window.location.reload();
                                });
                            });
                        });
                    });
                }
            });
        },
        page_score_apply_list: function () {
            var _this = this;

            new waterfall({
                auto_load: false,
                content_html: function (resp) {
                    return _this.render(require('text!./templates/score_apply_list.html'), resp.data);
                }
            }).start({
                spage: 1
            });
        },
        page_score_grant: function () {
            var _this = this;
            var uidTimeout;
            _this.$('#J_uid').on('change keyup', function () {
                var $this = $(this);
                var tele = $this.val();

                if (_.trim(tele).length != 11) {
                    return;
                }
                clearTimeout(uidTimeout);
                uidTimeout = setTimeout(function () {
                    utils.ajaxGet({a: 'ajax_grant_user', tele: tele}, function (resp) {
                        _this.$('#J_user_name').html(_.sprintf('%s%s', resp.data.tele, resp.data.realname ? "(" + resp.data.realname + ")" : ""));
                    }, function (resp) {
                        mask.error(resp.msg);
                        $this.val('');
                    })
                }, 500);
            });

            _this.$('form').validate({
                submitHandler: function (form) {
                    var params = _this.$('form').serializeJson();
                    utils.ajaxPost(_.extend({act: 'validate'}, params), function (resp) {
                        layer.confirm('转赠数量：' + resp.data.score_apply + ', 其中服务费用：' + resp.data.fee, function () {
                            utils.ajaxPost(params, function (resp) {
                                layer.closeAll();
                                mask.success(resp.msg, function () {
                                    window.location.reload();
                                });
                            });
                        });
                    });
                }
            });
        },
        page_score_grant_list: function () {
            var _this = this;
            new waterfall({
                auto_load: false,
                content_html: function (resp) {
                    return _this.render(require('text!./templates/score_grant_list.html'), resp.data);
                }
            }).start({
                spage: 1
            });
        },
        page_fans_list: function () {
            var _this = this;
            var ItemTpl = require('text!./templates/fans_list.html');
            var level = 1;

            var waterfall_list = new waterfall({
                spage: 1,
                auto_load: false,
                ajax_url: _.U({}),
                content_html: function (resp) {
                    return _this.render(ItemTpl, {
                        list: resp.data.list,
                        level: level
                    });
                },
                fn: function () {
                    _this.setupLazyLoad();
                }
            });
            waterfall_list.start({
                spage: 1
            });
            _this.$('.nav .item').click(function () {
                var $this = $(this);
                $this.addClass('pink').siblings().removeClass('pink');
                level = $this.data('level');

                waterfall_list.start({
                    spage: 1,
                    ajax_params: {
                        level: level
                    }
                });
            });
        },
        page_auth_name: function () {
            var _this = this;
            $('.js-submit-btn').on('click', function () {
                if ($('input[name="realname"]').val() == '') {
                    tip('请输入真实姓名');
                    return false;
                }
                if ($('input[name="cardid"]').val() == '') {
                    tip('请输入身份证号');
                    return false;
                }
                if ($('input[name="weixin"]').val() == '') {
                    tip('请输入微信');
                    return false;
                }
            });
            _this.submit_reload(_.base64_decode(_this.$('#J_from').val()));
        },
        page_auth_alipay: function () {
            var _this = this;
            _this.validate({
                fn: function (data) {
                    var url = _.base64_decode(_this.$('#J_from').val());
                    utils.ajaxPost(data, function (resp) {
                        mask.success(resp.msg, function () {
                            if (url) {
                                window.location.href = url;
                            }
                            else {
                                window.location.reload();
                            }
                        });
                    });
                }
            });
        },
        page_invite_qrcode: function () {
            var AgreementModal = require('group/common/agreement_modal');
            var _this = this;
            if (_this.$('input[name="qrcode_status"]').val() == 0 || _this.$('input[name="qrcode_status"]').val() == '') {
                new AgreementModal({
                    after_hide: function () {
                        utils.ajaxGet({a: 'invite_qrcode_update'}, function () {
                            window.location.reload();
                        });
                    }
                }).show({a: 'ajax_qrcode_agreement'});
            }
        },
        page_binding: function () {
            var _this = this;
            _this.$('.J_submit').click(function () {
                checkBindForm($('#bindForm'));
            });

            function checkBindForm(frm) {
                if ($(frm).find('input[name=password]').val() == '') {
                    tip('密码不能为空');
                    return false;
                }

                if ($(frm).find('input[name=password]').val() != $(frm).find('input[name=repassword]').val()) {
                    tip('两次密码不一致');
                    return false;
                }
                $(frm).submit();
            }
        },
        page_lottery: function () {
            $('.J_lottery_item').on('click',function(){
                $('.J_lottery_item').removeClass('ac').find('i').show();
                $(this).addClass('ac').find('i').hide();
            });

            $('.J_lottery_btn').on('click',function(){
                var item = $('.J_lottery_item.ac');
                if(item.length <= 0){
                    layer.msg('请选择奇偶数');
                    return false;
                }
                var type = item.data('type');
                var id = item.data('id');
                var oitem_id = item.data('mid');

                var msg = _.sprintf('确认选择%s,选择后不可更改,发货后不可退货.', type == 'odd' ? '奇数' : '偶数');

                layer.confirm(msg, {icon: 3, title:'提示'}, function(index){
                    layer.load(1);
                    utils.ajaxPost({order_id:id,order_item_id:oitem_id,type:type}, function (resp) {
                        layer.closeAll();
                        if(resp.status == 1){
                            layer.msg('抽奖已提交,请静待开奖!', {icon:6,time:800}, function(){
                                layer.load(1);
                                window.location.href = _.U({
                                    m: 'user',
                                    a: 'order',
                                    id: id
                                });
                            });
                            /*
                             if(resp.type == 1){
                             layer.msg('没中奖,再接再厉吧', {icon:5,time:800}, function(){
                             layer.load(1);
                             window.location.href = _.U({
                             m: 'user',
                             a: 'order_info',
                             id: id
                             });
                             });
                             }else{
                             layer.msg('中奖啦!', {icon:6,time:800}, function(){
                             layer.load(1);
                             window.location.href = _.U({
                             m: 'user',
                             a: 'order_address',
                             id: id
                             });
                             });
                             }
                             */
                        }else{
                            layer.msg(resp.msg);
                        }
                    });
                });
            });
        },
        page_order_address: function () {
            var _this = this;
            _this.$('.J_select').click(function (e) {
                var $item = $(this).parents('.J_item');
                utils.ajaxPost({order_id:$item.data('oid'),address_id:$item.data('id')}, function (resp) {
                    window.location.href = _.U({
                        m: 'user',
                        a: 'order_info',
                        id: $item.data('oid')
                    });
                });
            });
        },
        page_recharge: function () {
            var _this = this;
            _this.$('input[name="pricetype"]').on('click',function(){
                if($(this).val()>0){
                    $('.score-input').hide();
                }else{
                    $('.score-input').show();
                }
            });
            _this.validate({
                fn: function (params) {
                    if($('input[name="pricetype"]:checked').val()==0){
                        if (_.empty($('input[name="price"]').val())) {
                            return layer.msg('金额不能为空!');
                        }
                        if (isNaN($('input[name="price"]').val())) {
                            return layer.msg('金额必须为数字!');
                        }
                        if (_.floatval($('input[name="price"]').val()) <= 0) {
                            return layer.msg('金额必须大于0!');
                        }
                    }
                    utils.ajaxPost(params, function (resp) {
                        window.location.href = resp.data.url;
                    });
                }
            });

        },
        page_wallet: function () {
            var _this = this;
            _this.waterfall();
        },
        page_cash: function () {
            var _this = this;
            _this.validate({
                fn: function (params) {
                    if (_.empty($('input[name="price"]').val())) {
                        return layer.msg('金额不能为空!');
                    }
                    if (isNaN($('input[name="price"]').val())) {
                        return layer.msg('金额必须为数字!');
                    }
                    if (_.floatval($('input[name="price"]').val()) <= 0) {
                        return layer.msg('金额必须大于0!');
                    }
                    utils.ajaxPost(params, function (resp) {
                        layer.msg('已提交到管理员处理!', {icon:6,time:800}, function(){
                            window.location.reload();
                        });

                    });
                }
            });
        },
        page_certification: function () {
            var _this = this;
            _this.validate({
                fn: function (params) {
                    utils.ajaxPost(params, function (resp) {
                        window.location.href = $('input[name="ret_url"]').val();
                    });
                }
            });

            _this.initUpload({
                queueSizeLimit: 1,
                removeCompleted: true,
                onUpload: function () {
                    _this.$('.uploadifive-queue').show();
                },
                _onUploadComplete: function (file, data) {
                    _this.$('.uploadifive-queue').hide();
                    _this.$('.upload_erweima .erweima').attr('src', data.data.fullPath);
                    _this.$('#J_img_hidden').val(data.data.savePath);
                }
            });

        },
        page_lower: function () {
            var _this = this;
            _this.waterfall();
        },
        page_commission: function () {
            var _this = this;
            _this.waterfall();
            $(function(){
                $('.js-show-search').click(function(){
                    $('.js-search-box').slideToggle('fast',function(){
                        if($('.js-search-box').is(':hidden')){
                            $('.js-show-search').text('搜索');
                        }else{
                            $('.js-show-search').text('取消搜索');
                        }
                    });

                });
            });
        },
        page_lower_commission: function () {
            var _this = this;
            _this.waterfall();
            $(function(){
                $('.js-show-search').click(function(){
                    $('.js-search-box').slideToggle('fast',function(){
                        if($('.js-search-box').is(':hidden')){
                            $('.js-show-search').text('搜索');
                        }else{
                            $('.js-show-search').text('取消搜索');
                        }
                    });

                });
            });
        },
    });
});